package com.yidong.laidian.laidian.controller;

import com.yidong.laidian.laidian.dataobject.UsersDO;
import com.yidong.laidian.laidian.enums.ResultEnum;
import com.yidong.laidian.laidian.execption.ApiViewException;
import com.yidong.laidian.laidian.form.UserForm;
import com.yidong.laidian.laidian.service.UserService;
import com.yidong.laidian.laidian.util.ResultVoUtils;
import com.yidong.laidian.laidian.vo.Person;
import com.yidong.laidian.laidian.vo.ResultVO;
import com.yidong.laidian.laidian.vo.UserVO;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class IndexController {
    private final UserService userService;

    @GetMapping("/users/list")
    public ResultVO<Object>findAllUsers(){
        return ResultVoUtils.success(userService.getUserList());
    }



    @PostMapping("/users")
    public ResultVO<Object> createUserForm(@Valid @RequestBody UserForm userForm, BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            System.out.println("错误信息：");
            System.out.println(bindingResult.getFieldError().getDefaultMessage());

//            return ResultVoUtils.error(
//                    ResultEnum.ACCOUNT_EXIST.getCode(),
//                    bindingResult.getFieldError().getDefaultMessage()
//            );

//            throw new RuntimeException();

            throw new ApiViewException(ResultEnum.ACCOUNT_NOT_EXIST.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }

        //接收到users数据，保存到数据库
        UsersDO usersDO = new UsersDO();
        usersDO.setName(userForm.getName());
        usersDO.setPassword(userForm.getPassword());
        usersDO.setEmail(userForm.getEmail());
        usersDO.setPhone(userForm.getPhone());
        usersDO.setAge(userForm.getAge());

       UsersDO save = userService.save(usersDO);

//        return ResultVoUtils.success(userForm);
        return ResultVoUtils.success(save);
    }

    @GetMapping("/")
    public String index() {
        UserVO userVO = new UserVO();

        userVO.setName("zero");
        userVO.setSex("女");
        userVO.setAge(20);

        userVO.getName();
        userVO.getSex();
        userVO.getAge();

//        System.out.println(userVO.toString());

        System.out.println("--------------");

        Person person = new Person();

        person.setName("lisi");
        person.setAge(30);
        person.setGender("男");

        person.getAge();

        System.out.println(person.toString());


        return "zero";


    }


}
